const { creteTitle, findTitles, delTitle } = require("../model/titleModel");
const { crawler } = require("../utils/crawler");
//新增
const addTitle = async (req, res, next) => {
  const result = await creteTitle(req.body);
  if (result) {
    res.send({ httpStatus: 200, data: result, msg: "增加成功" });
  } else {
    res.send({ httpStatus: 400, data: [], msg: "增加出错" });
  }
};
//查询
const getTitles = async (req, res) => {
  console.log("title");
  const result = await findTitles();
  if (result.length || result.length === 0) {
    res.send({ httpStatus: 200, total: result.length, data: result });
  } else {
    res.send({ httpStatus: 400, msg: "查询出错", date: [] });
  }
};

//删除
const deleteTitle = async (req, res) => {
  const { _id } = req.query;
  const query = { _id };
  const result = await delTitle(query);
  if (result.n) {
    res.send({ httpStatus: 200, state: true, msg: "删除成功" });
  } else {
    res.send({ httpStatus: 400, state: false, msg: "删除出错" });
  }
};

const autoGenerate = async (req, res) => {
  try{
    crawler(req.query.url)
    res.send({ httpStatus: 200, state: true, msg: "删除成功" });
  }catch(error){
    res.send({ httpStatus: 400, state: false, msg: "删除出错" });
  }
 
};

module.exports = {
  addTitle,
  getTitles,
  deleteTitle,
  autoGenerate,
};
